package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

/**
 * 文件上传下载
 */
@RestController
@Slf4j
@RequestMapping("/common")
public class CommonController {

    @Value("${reggie.path}")
    private String path;
    /**
     * 接收文件上传
     * //接收到的文件是个临时文件，需要转存到别的位置，要不请求结束就删除了
     * @param file 必须跟前台name保持一致
     * @return
     */
    @PostMapping("/upload")
    public R<String> uplaod(MultipartFile file) throws IOException {
        log.info(file.toString());
        //原始文件名
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //防止覆盖，UUID随机生成文件名
        String uuFileNmae = UUID.randomUUID().toString()+suffix;
        //判断目录存在不存在,不存在创建一个
        File dir = new File(path);
        if(!dir.exists()){
            dir.mkdirs();
        }
        //转存到指定位置
        file.transferTo(new File(path+uuFileNmae));
        return R.success(uuFileNmae);
    }

    /**
     * 文件下载
     * @param name
     * @param response
     */
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) throws IOException {
        //输入流读取文件内容
        FileInputStream inputStream = new FileInputStream(new File(path+name));

        //输出流，将文件写回浏览器
        ServletOutputStream outputStream  = response.getOutputStream();

        response.setContentType("image/jpeg");

        int len = 0;
        byte[] bytes = new byte[1024];
        while ((len = inputStream.read(bytes)) != -1){
            outputStream.write(bytes,0,len);
            outputStream.flush();
        }

        //关闭资源
        outputStream.close();
        inputStream.close();
    }
}
